package com.test.mylotterysystem.comment.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean set(String key, String value) {
        try {
            if (!StringUtils.hasText(key)) {
                return false;
            }
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("redis中set操作发生异常");
            return false;
        }
    }

    public boolean set(String key, String value, long timeout) {
        try {
            if (!StringUtils.hasText(key)) {
                return false;
            }
            stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("redis中set操作发生异常");
            return false;
        }
    }

    public String get(String key) {
        try {
            if (!StringUtils.hasText(key)) {
                return null;
            }
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("redis中get操作发生异常");
            return null;
        }
    }

    public boolean delete(String... keys) {
        try {
            if (keys == null || keys.length == 0) {
                return false;
            } else {
                if (keys.length == 1) {
                    stringRedisTemplate.delete(keys[0]);
                } else {
                    stringRedisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(keys));
                }
                return true;
            }
        } catch (Exception e) {
            log.error("redis中delete操作发生异常");
            return false;
        }

    }
}
